<template>
    <div class="main" style="width: 100%;height:100%;overflow-y: auto;" >
        <el-button type="primary" plain style="width: 90px;margin-top: 10px;position:relative;left:20px;" @click="clear">一键清空</el-button>
        <el-button type="primary" plain style="width: 90px;margin-top: 10px;position:relative;left:15px;" @click="DownloadToWord">下载为word</el-button>
        <el-tooltip
            class="box-item"
            effect="dark"
            content="加入收藏夹"
            placement="top-start"
        >
            <el-button type="warning" :icon="Star" circle  style="margin-top: 10px;position: relative;left:190px;" @click="openCollection"/><!-- 打开收藏夹列表 -->
        </el-tooltip>
        <ul  style="list-style-type: none; padding-top: 20px;padding-left: 20px; margin: 0px;">
            <li    style="width: 420px;border-radius: 10px;margin-bottom: 10px;position:relative;"
                v-for="(item, index) in Store.$state.Question.Confirm"
                :key="index"
                >
                <text class="t">{{index+1}}、{{ Store.$state.Question.Confirm[index].content }}</text>
                <br/>
                <div 
                    style="display: flex; flex-wrap: wrap; gap: 10px;"
                    >
                    <div 
                        v-for="(item, index1) in Store.$state.Question.Confirm[index].image" 
                    >
                        <el-image 
                        style="height: 150px; width: 100%;" 
                        :src="item.url"
                        :zoom-rate="1.2"
                        :max-scale="7"
                        :min-scale="0.2"
                        :preview-src-list="Store.$state.Question.Confirm[index].image.map(img => img.url)"
                        show-progress
                        fit="cover"
                        >
                        <template #error>
                            <div class="image-slot">
                            <el-icon><icon-picture /></el-icon>
                            </div>
                        </template>
                        </el-image>
                    </div>
                    </div>
                <br/>
                <text class="t">答案：{{ Store.$state.Question.Confirm[index].answer }}</text>
                <el-button type="primary" plain @click="deleteQuestionFromConfirm(index)" style="width: 100px;margin-top: 0px;position:relative;left:300px;">重新编辑</el-button>
            </li>
        </ul>
        <el-dialog v-model="dialogVisible" title="选择习题需要保存到的文件" width="300px" height="420px">
      <Collect @close-dialog="closeCollection" />
    </el-dialog>
    </div>
</template>
<script setup lang="ts">
import { useCounterStore } from '@/stores/counter';
const Store = useCounterStore();
import { ref } from 'vue';
import { Download, Picture as IconPicture, Star } from '@element-plus/icons-vue';


function deleteQuestionFromConfirm(index: any) {
    Store.deleteQuestionFromConfirm(index);
}

function clear() {
    let confirmList = Store.$state.Question.Confirm;
    for (let i = confirmList.length - 1; i >= 0; i--) {
        Store.deleteQuestionFromConfirm(i);
    }
}
 
import { Document, Packer, Paragraph, TextRun, ImageRun, AlignmentType } from 'docx';
import { saveAs } from 'file-saver';

// 辅助函数：获取图片的宽高比
const getImageDimensions = (url: string): Promise<{ width: number; height: number }> => {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.onload = () => {
      resolve({ width: img.width, height: img.height });
    };
    img.onerror = (error) => {
      reject(error);
    };
    img.src = url;
  });
};

// 辅助函数：将图片 URL 转换为 Uint8Array
const fetchImage = async (url: string) => {
  const response = await fetch(url);
  const arrayBuffer = await response.arrayBuffer();
  return new Uint8Array(arrayBuffer);
};

const DownloadToWord = async () => {
  // 弹出一个对话框，让用户输入文件名
  const fileName = prompt('请输入文件名（无需后缀）', '习题');
  if (!fileName) {
    alert('文件名不能为空！');
    return;
  }

  // 创建一个数组来存储所有的段落
  const children: Paragraph[] = [];

  // 添加标题（居中对齐）
  children.push(
    new Paragraph({
      alignment: AlignmentType.CENTER, // 居中对齐
      children: [
        new TextRun({
          text: '习题文档', // 标题内容
          bold: true,
          size: 36, // 设置字体大小
          font: '微软雅黑', // 设置字体
        }),
      ],
      spacing: { after: 400 }, // 设置段后间距
    }),
  );

  // 遍历确认题目
  for (const [index, item] of Store.$state.Question.Confirm.entries()) {
    // 添加题目序号和内容
    children.push(
      new Paragraph({
        children: [
          new TextRun({
            text: `${index + 1}、${item.content.replace(/\n/g, '\n')}`, // 处理换行符
            bold: true,
            size: 24, // 设置字体大小
            font: '微软雅黑', // 设置字体
          }),
        ],
        spacing: { after: 200 }, // 设置段后间距
      }),
    );

    // 添加图片
    for (const img of item.image) {
      const imageData = await fetchImage(img.url); // 获取图片数据
      const dimensions = await getImageDimensions(img.url); // 获取图片原始宽高
      const targetWidth = 300; // 设置目标宽度
      const targetHeight = (dimensions.height / dimensions.width) * targetWidth; // 根据宽高比计算目标高度

      children.push(
        new Paragraph({
          alignment: AlignmentType.CENTER, // 图片居中
          children: [
            new ImageRun({
              data: imageData,
              transformation: {
                width: targetWidth,
                height: targetHeight, // 动态设置高度
              },
            }),
          ],
          spacing: { after: 200 }, // 设置段后间距
        }),
      );
    }

    // 添加答案
    children.push(
      new Paragraph({
        children: [
          new TextRun({
            text: `答:${item.answer.replace(/\n/g, '\n')}`,
            bold: true,
            size: 24,
            highlight: 'yellow', // 背景色（黄色）
            font: '微软雅黑',
          }),
        ],
        spacing: { after: 200 }, // 设置段后间距
      }),
    );
  }

  // 创建 Document 实例，并将所有段落添加到同一个 section 中
  const doc = new Document({
    sections: [
      {
        properties: {},
        children, // 将所有段落添加到同一个 section
      },
    ],
  });

  // 生成并保存文档
  const blob = await Packer.toBlob(doc);
  saveAs(blob, `${fileName}.docx`); // 使用用户输入的文件名
};



import Collct from './Collect.vue'
const dialogVisible = ref(false);// 控制弹出框的显示与隐藏
function openCollection(){
  dialogVisible.value = true;
};
function closeCollection(){
  dialogVisible.value = false;
};
</script>

<style scoped>

 
div[style*="overflow-y: auto"]::-webkit-scrollbar {
  width: 6px;
  background-color: #f3f4f8;
}
 
div[style*="overflow-y: auto"]::-webkit-scrollbar-track {
    background: #e3e6e9e3;
}
 
div[style*="overflow-y: auto"]::-webkit-scrollbar-thumb {
  background: #c2d0df;
  border-radius: 6px;
}
 
div[style*="overflow-y: auto"]::-webkit-scrollbar-thumb:hover {
  background: #a0a0a0;
}
.t{
    white-space: normal;
    word-wrap: break-word;
    display:block;
}
</style>